import { useParams } from 'react-router-dom';
import { useEffect, useState } from 'react';
import { agentsAPI, type Agent } from '@/lib/apiClient';
import IframeLoader from './IframeLoader';
import { Card, CardContent } from '@/components/ui/card';
import { AlertCircle, Loader2 } from 'lucide-react';

/**
 * 智能体查看页面
 * 根据 ID 加载对应的智能体并显示在 iframe 中
 */
export default function AgentView() {
  const { id } = useParams<{ id: string }>();
  const [agent, setAgent] = useState<Agent | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!id) {
      setError('缺少智能体 ID');
      setLoading(false);
      return;
    }

    // 从数据库API加载智能体
    const loadAgent = async () => {
      try {
        const response = await agentsAPI.getById(id);
        setAgent(response.agent);
      } catch (err) {
        setError('智能体不存在');
        console.error('Failed to load agent:', err);
      } finally {
        setLoading(false);
      }
    };

    loadAgent();
  }, [id]);

  if (loading) {
    return (
      <div className="flex h-[calc(100vh-8rem)] items-center justify-center">
        <div className="flex flex-col items-center gap-4">
          <Loader2 className="h-8 w-8 animate-spin text-primary" />
          <p className="text-muted-foreground">加载中...</p>
        </div>
      </div>
    );
  }

  if (error || !agent) {
    return (
      <Card className="border-destructive">
        <CardContent className="flex flex-col items-center gap-4 py-12">
          <AlertCircle className="h-12 w-12 text-destructive" />
          <div className="text-center">
            <h3 className="text-lg font-semibold">加载失败</h3>
            <p className="text-sm text-muted-foreground">
              {error || '智能体不存在'}
            </p>
          </div>
        </CardContent>
      </Card>
    );
  }

  return <IframeLoader url={agent.url} name={agent.name} />;
}

